package com.atguigu.rabbitmqtest.threetest;

import com.atguigu.rabbitmqtest.utils.RabbitMqUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConfirmCallback;

import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;

public class Producer {
    private static final String QUEUE_NAME = "ack_confirm_queue";

    public static void main(String[] args) throws Exception {
        ConcurrentSkipListMap<Long, String> concurrentSkipListMap = new ConcurrentSkipListMap<>();
        Channel channel = RabbitMqUtils.getChannel();
        channel.confirmSelect();
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        ConfirmCallback ackCallback = (deliveryTag, multiple) -> {
            if (multiple) {
                ConcurrentNavigableMap<Long, String> headMap = concurrentSkipListMap.headMap(deliveryTag);
                headMap.clear();
            }
            concurrentSkipListMap.remove(deliveryTag);
            System.out.println("消息发送成功了"+deliveryTag);
        };
        ConfirmCallback nackCallback = (deliveryTag, multiple) -> {
            System.out.println("消息发送失败"+deliveryTag);
            System.out.println("失败的消息有："+concurrentSkipListMap);
        };
        channel.addConfirmListener(ackCallback, nackCallback);

        for (int i = 1; i <= 1000; i++) {
            String message = "消息" + i;
            channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8"));
            concurrentSkipListMap.put(channel.getNextPublishSeqNo(),message);
        }

    }
}
